import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module_common/network/rpc.dart';
import 'package:aichat_flutter_wallet/module_common/provider/token_info_provider.dart';
import 'package:aichat_flutter_wallet/module_common/provider/token_list_provider.dart';
import 'package:aichat_flutter_wallet/module_common/provider/wallet_info_provider.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/header/page_header.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/token_widget/token_logo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_database/objectbox.dart';
import 'package:lib_util/lib_util.dart';

import '../utils/index.dart';

class TradeTransactionsPageDetails extends StatefulWidget {
  Token token;
  TransactionBean transaction;
  String? rpc;
  //  主链 的 币种符号 symbol
  String? parentSymbol;
  Chain? chainItem;
  TradeTransactionsPageDetails({super.key, required this.token, required this.transaction,this.rpc,this.chainItem,this.parentSymbol});
  @override
  _TradeTransactionsPageDetails createState() => _TradeTransactionsPageDetails();
}

class _TradeTransactionsPageDetails extends State<TradeTransactionsPageDetails> {
  String? gasFee;
  String? block;

  late TransactionDetails? transactionDetails = TransactionDetails(
      gasFee: '0.00',
      block: '0.00',
      chainId: '56',
      value: '0.00',
      hash: '--',
      status: 1,
      contractAddress: null,
      toAddress: '--',
      formAddress: '--',
      time: '0');
  _init() {
    if ((Utils.isNotEmpty(widget.transaction.txFee) && Utils.isNotEmpty(widget.transaction.height)) &&
        (Utils.isNotEmpty(widget.transaction.state) && widget.transaction.state == '1')) {
      gasFee = widget.transaction.txFee;
      block = widget.transaction.height;
      try {
        double? gas = double.tryParse(gasFee!) ?? 0;
        if (gas > 10) {
          gasFee = null;
          fetchData();
        }
      } catch (e) {
        Log().d('gas error');
      }
    } else {
      kaiPrint('_init  ${widget.rpc}');
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        fetchData();
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _init();
  }

  Widget tradeStatus({int index = 2}) {
    List<String> urlList = [
      'assets/images/wallet-trade/trade-fail.png',
      'assets/images/wallet-trade/trade-success.png',
      'assets/images/wallet-trade/trade-pending.png',
    ];
    List<String> textList = [
      'Failed',
      'Successed',
      'Pending',
    ];
    List<Color> colorList = [
      AppColors.c_E0421C,
      AppColors.c_3AB197,
      AppColors.c_FFA41A,
    ];
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Image.asset(
          urlList[index],
          width: 14.w,
          height: 14.w,
          fit: BoxFit.fitHeight,
        ),
        SizedBox(
          width: 5.w,
        ),
        Text(textList[index],
            style: TextStyle(
              fontSize: 12.sp,
              fontWeight: FontWeight.w400,
              color: colorList[index],
            ))
      ],
    );
  }

  void fetchData() async {
    try {
      String rpc = '';
      if(widget.rpc == null){
        Chain c = context.read<WalletInfoNotifier>().walletChain!;
        rpc= await ObjectBox().nodeInfoModel.getSelectedNodeInfo(c.shortName).url;
      } else{
        rpc= widget.rpc!;
      }
      String hash = widget.transaction.txId!;
      if (hash.isEmpty) return;
      TransactionDetails data = await RpcClient().ethTransactionDetails(rpc: rpc, txHash: hash);
      //  查询 钱包地址
      // setState(() {
      //   transactionDetails = data;
      // });
      if (mounted) {
        if (Utils.isNotEmpty(data.gasFee) && Utils.isNotEmpty(data.block) && int.parse(data.block) != 0) {
          setState(() {
            gasFee = data.gasFee;
            block = data.block;
            widget.transaction.pending = false;
            widget.transaction.txFee = gasFee;
            widget.transaction.state = data.status.toString();
            widget.transaction.height = block;

            if(widget.rpc==null){
              context.read<TokenInfoNotifier>().updateTranDetails(widget.transaction);
              ObjectBox().transactionModel.updatePendingTransactionState(widget.transaction);
              context.read<TokenListNotifier>().updateTokenBalance(widget.token).then((val) {
                context.read<TokenInfoNotifier>().updateToken(val);
              });
            }
          });
        }
      }
    } catch (e) {
      kaiPrint(e);
    }
  }

  Widget LeftRightTextWidget(String leftText, String rightText, {bool useCopy = false, dynamic copyText = ''}) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          leftText,
          style: TextStyle(fontSize: 13.sp, color: AppColors.c_868391, fontWeight: FontWeight.w400),
        ),
        SizedBox(
          width: 50.w,
        ),
        Expanded(
            child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Text(
                rightText,
                softWrap: true,
                maxLines: 2,
                textAlign: TextAlign.right,
                style: TextStyle(
                    fontSize: 13.sp, height: 18.w / 13.w, fontWeight: FontWeight.w400, color: AppColors.c_333333),
              ),
            ),
            if (useCopy)
              SizedBox(
                width: 3.w,
              ),
            if (useCopy)
              GestureDetector(
                onTap: () {
                  if (copyText == '' || copyText == null) return;
                  bool isCopySuccess = Utils.copyText(copyText);
                  Toast.show(context,
                      position: Dpositon.top,
                      message: isCopySuccess ? 'Copied successfully' : 'Copy failed',
                      status: isCopySuccess ? '1' : '2');
                },
                child: Image.asset('assets/images/common/copy.png', width: 16.w, height: 16.w),
              )
          ],
        )),
      ],
    );
  }

  String callBackTransactionType({isBool = false}) {
    String from = widget.transaction.from!;
    bool send = from.toLowerCase() == widget.token.getWalletInfo()!.address.toLowerCase();
    if (!isBool && send)
      return 'Transfer';
    else if (!isBool && !send)
      return 'Receive';
    else if (isBool && send)
      return '-';
    else if (isBool && !send)
      return '+';
    else
      return '';
  }

  String callBackFormatTime(String time) {
    if (time == '0') {
      return 'YYYY/MM/DD HH:mm:ss';
    }
    int currentTime = int.parse(time);
    return Utils.formatDateTime(currentTime);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          color: AppColors.c_white,
          child: Column(
            children: [
              PageHeaderCom(title: 'Transaction Details', showBottomBorder: false),
              SizedBox(
                height: 20.w,
              ),
              Stack(
                clipBehavior: Clip.none,
                children: [
                  TokenLogo(
                    token: widget.token,
                    size: 40.w,
                  ),
                  Visibility(
                      visible: widget.token.contractType != TokenType.native.name,
                      child: Positioned(
                        right: -3.w,
                        bottom: -1.w,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(16.w),
                          child: PublicImage(
                              width: 16.w, height: 16.w,
                              image: widget.chainItem!=null? widget.chainItem!.logo:context.read<WalletInfoNotifier>().walletChain!.logo),
                        ),
                      ))
                ],
              ),
              SizedBox(
                height: 10.w,
              ),
              Text(
                '${callBackTransactionType(isBool: true)}${Utils.formatStringBalance(widget.transaction.amount, fractionDigits: 18, trimDecimalZero: true)} ${widget.token.symbol}',
                style: TextStyle(
                  fontSize: 22.sp,
                  fontWeight: FontWeight.bold,
                  fontFamily: '_Din',
                  color: AppColors.c_333333,
                ),
              ),
              SizedBox(
                height: 5.w,
              ),
              Text(callBackTransactionType(),
                  style: TextStyle(
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w400,
                    color: AppColors.c_BEBDCA,
                  )),
              SizedBox(
                height: 10.w,
              ),
              tradeStatus(
                  index: int.parse((widget.transaction.state == 'null' || widget.transaction.state!.isEmpty)
                      ? '0'
                      : widget.transaction.state!)),
              Container(
                height: 30.w,
                decoration: BoxDecoration(
                  border: Border(bottom: BorderSide(color: AppColors.c_F3F2F7, width: 1.w)),
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(vertical: 15.w, horizontal: 20.w),
                child: Column(
                  children: [
                    Visibility(
                      visible: widget.transaction.tokenContractAddress != '',
                      child: LeftRightTextWidget(
                          'Contract address',
                          Utils.formatAddress(
                            widget.transaction.tokenContractAddress ?? '--',
                          ),
                          useCopy: true,
                          copyText: widget.transaction.tokenContractAddress),
                    ),
                    Visibility(
                      visible: widget.transaction.tokenContractAddress != '',
                      child: SizedBox(
                        height: 15.w,
                      ),
                    ),
                    LeftRightTextWidget(
                        'From',
                        Utils.formatAddress(
                          widget.transaction.from!,
                        ),
                        useCopy: true,
                        copyText: widget.transaction.from!),
                    SizedBox(
                      height: 15.w,
                    ),
                    LeftRightTextWidget(
                        'To',
                        Utils.formatAddress(
                          widget.transaction.to!,
                        ),
                        useCopy: true,
                        copyText: widget.transaction.to!),
                    SizedBox(
                      height: 15.w,
                    ),
                    LeftRightTextWidget('Total gas fee',
                        '${Utils.isEmpty(gasFee) ? '-' : Utils.formatStringBalance(gasFee, fractionDigits: Config.gasFeeFixedNum, trimDecimalZero: true)} ${widget.parentSymbol!=null?widget.parentSymbol:widget.token.getChain()!.symbol}'),
                    SizedBox(
                      height: 15.w,
                    ),
                    Divider(
                      height: 1.w,
                      color: AppColors.c_F3F2F7,
                    ),
                    SizedBox(
                      height: 15.w,
                    ),
                    LeftRightTextWidget(
                        'Hash',
                        Utils.formatAddress(
                          widget.transaction.txId!,
                        ),
                        useCopy: true,
                        copyText: widget.transaction.txId!),
                    SizedBox(
                      height: 15.w,
                    ),
                    LeftRightTextWidget('Block height', Utils.isEmpty(block) ? '-' : block!,
                        useCopy: true, copyText: block),
                    SizedBox(
                      height: 15.w,
                    ),
                    LeftRightTextWidget('Time', widget.transaction.getFormatTransactionTime()),
                    SizedBox(
                      height: 15.w,
                    ),
                    Divider(
                      height: 1.w,
                      color: AppColors.c_F3F2F7,
                    ),
                    SizedBox(
                      height: 15.w,
                    ),
                    GestureDetector(
                      onTap: () {
                        TranUtils.goBlockChainScan(context,widget.chainItem!=null? widget.chainItem:widget.token.getChain(), txId: widget.transaction.txId);
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Image.asset('assets/images/wallet-trade/browser.png', width: 16.w, height: 16.w),
                              SizedBox(
                                width: 10.w,
                              ),
                              Text(
                                'Go to the blockchain explorer',
                                style:
                                    TextStyle(fontSize: 13.sp, fontWeight: FontWeight.w400, color: AppColors.c_333333),
                              ),
                            ],
                          ),
                          Expanded(
                            child: Container(),
                            flex: 1,
                          ),
                          Image.asset('assets/images/common/more.png', width: 12.w, height: 12.w)
                        ],
                      ),
                    )
                  ],
                ),
              )
            ],
          )),
    );
  }
}
